﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpShare.Storage.Filter {
    public class FilteredStorageProvider : FilteredStorageContainer, IStorageProvider {
        private EventHandler _contentsChangedHandler;

        public FilteredStorageProvider(IStorageProvider baseProvider, IStorageFilter filter)
            : base(baseProvider, filter, null) {

        }

        public new IStorageProvider BaseItem { get { return (IStorageProvider)base.BaseItem; } }

        #region IStorageProvider Members

        public event EventHandler ContentsChanged {
            add {
                _contentsChangedHandler += value;
                this.BaseItem.ContentsChanged += new EventHandler(BaseItemContentsChanged);
            }
            remove {
                _contentsChangedHandler -= value;
                if (_contentsChangedHandler == null) {
                    this.BaseItem.ContentsChanged -= BaseItemContentsChanged;
                }
            }
        }

        public ulong AvailableBytes {
            get { return BaseItem.AvailableBytes; }
        }

        public ulong TotalBytes {
            get { return BaseItem.TotalBytes; }
        }

        public Searching.IStorageSearchEngine SearchEngine {
            get {
                Searching.IStorageSearchEngine baseEngine = this.BaseItem.SearchEngine;
                if (baseEngine == null)
                    return null;
                return new FilteredSearchEngine(baseEngine, this);
            }
        }

        #endregion

        private void BaseItemContentsChanged(object sender, EventArgs e) {
            if (_contentsChangedHandler != null) {
                try {
                    _contentsChangedHandler(this, EventArgs.Empty);
                } catch { }
            }
        }
    }
}
